<template>
  <!-- 弹框 -->
  <el-dialog
  :title="btnType==0?'添加':'编辑'"
  :visible.sync="dialogVisible"
  width="40%"
  :before-close="handleClose">
  <!-- 弹框内容 -->
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">

  <el-form-item label="用户 ID" prop="userid" v-if="btnType==0?false:true">
    <el-input v-model="ruleForm.userid" clearable :disabled="true"></el-input>
  </el-form-item>
  <el-form-item label="用户昵称" prop="usernick">
    <el-input v-model="ruleForm.usernick" clearable></el-input>
  </el-form-item>
  <el-form-item label="会员电话" prop="memberphone">
    <el-input v-model="ruleForm.memberphone" clearable></el-input>
  </el-form-item>
  <el-form-item label="消费金额" prop="pay">
    <el-input v-model.number="ruleForm.pay" clearable></el-input>
  </el-form-item>
  <el-form-item label="订单总数" prop="orders">
    <el-input v-model.number="ruleForm.orders" clearable></el-input>
  </el-form-item>
  <el-form-item label="会员等级" prop="memberlv" :disabled="true">
    <el-select v-model.number="ruleForm.memberlv" placeholder="请选择会员等级"  :disabled="btnType==0?false:true">
      <el-option label="1" value="1"></el-option>
      <el-option label="2" value="2"></el-option>
      <el-option label="3" value="3"></el-option>
    </el-select>
  </el-form-item>
  <el-form-item label="消费时间" prop="date">
      <el-autocomplete
        class="inline-input"
        v-model="ruleForm.date"
        :fetch-suggestions="querySearch"
        placeholder="请消费时间"
        @select="handleSelect"
        prefix-icon="el-icon-date"
        clearable
        :disabled="btnType==0?false:true"
      ></el-autocomplete>
  </el-form-item>

   <el-form-item label="账户禁用" prop="disableuser">
    <el-select v-model.number="ruleForm.disableuser" placeholder="请选择是否禁用账户">
      <el-option label="是" :value="true"></el-option>
      <el-option label="否" :value="false"></el-option>
    </el-select>
  </el-form-item>

</el-form>

  <span slot="footer" class="dialog-footer">
    <el-button @click="closefun">取 消</el-button>
    <el-button type="primary" @click="submitForm('ruleForm')">提 交</el-button>
  </span>
</el-dialog>
</template>

<script>
import { addStudentApi,editStudentApi } from '@/api/studentApi'
 export default {
    // 建议输入框生命周期
    mounted() {
      this.restaurants = this.loadAll()
      // this.ruleForm = this.row //浅拷贝,修改的是同一个对象的引用
      // this.ruleForm = { ...this.row }
      // 将数据转变成字符串,再转回对象,就不会引用同一个对象
      this.ruleForm = JSON.parse(JSON.stringify(this.row))
      
    },
    props:['row','btnType'],
    data() {
      // 自定义验证规则函数 ---支付金额
      var validatorMypay = (rule, value, callback) => {
        if (value === '' || value == null) {
          callback(new Error('请输入支付金额'))
        } else if(value >= 20000){
          callback(new Error('单次消费不可超过20000元'))
        }
        else {
          callback()
        }
      };
      //订单总数验证规则
      var validatorMyorders = (rule, value, callback) => {
        if (value === '' || value == null) {
          callback(new Error('请输入订单数量'))
        } else if(value >= 500){
          callback(new Error('订单总数不能超过500'))
        }
        else {
          callback();
        }
      };

      return {
        dialogVisible: true,
        ruleForm:{
          // 双向绑定一个属性
          id:'',
          userid: '',
          usernick:'',
          memberphone:'',
          pay:'',
          orders:'',
          memberlv:'',
          date:'',
          disableuser:'',
        },
        rules:{ 
          //rules对应上面的属性的验证规则，prop
          // userid:[// 自定义规则
          //   {required: true,validator:validatorMyorders, trigger: 'blur'}
          // ],
          userid:[
            { required: true, message: '请输入用户ID', trigger: 'blur' },
            { min: 7, max: 7, message: '你输入ID格式有误,请输入7位数ID!', trigger: 'blur'}
          ],
          usernick:[
            { required: true, message: '请输入用户昵称', trigger: 'blur' },
            { min: 1, max: 10, message: '格式有误,长度不可超过10个字符', trigger: 'blur'}
          ],
          memberphone:[
            { required: true, message: '请输入会员电话', trigger: 'blur' },
            { min: 11, max: 11, message: '请输入11位数会员电话', trigger: 'blur'},
          ],
          pay:[
            {required: true,validator:validatorMypay, trigger: 'blur'}
          ],
           orders:[
            {required: true,validator:validatorMyorders, trigger: 'blur'}
          ],
          memberlv: [
            { required: true, message: '请选择会员等级', trigger: 'change' }
          ],
           date: [
            { required: true, message: '请选择消费时间', trigger: 'change' }
          ],
           disableuser: [
            { required: true, message: '请选择是否禁用', trigger: 'change' }
          ],
        },
        //建议输入框变量
        restaurants: [],
        state1: '',
      };
    },
    methods: {
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
            this.closefun()
          })
          .catch(_ => {});
      },
      // 关闭弹窗
      closefun(){
        this.$emit('closeDialog')
      },
      // 提交表单时触发验证
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 获取from的值,发送请求给后端,后端执行添加逻辑,通知前端添加成功,刷新表格
            if(this.btnType == 0){ //提交按钮在btnType为0执行添加
                  addStudentApi(this.ruleForm).then(res=>{
                  if(res.code == 200){
                    this.$emit('closeDialog') // 关闭弹窗
                    this.$emit('resettable') //刷新表格
                    this.$message({message: '添加成功!',center: true,type: 'success'});
                  }
                })
              }else{  //提交按钮在btnType为1执行编辑
                  editStudentApi(this.ruleForm).then(res=>{
                    if(res.code == 200){
                      this.$emit('closeDialog') // 关闭弹窗
                      this.$emit('resettable') //刷新表格
                      this.$message({message: '编辑成功!',center: true,type: 'success'});
                    }
                  })
              }
          }
           else {
            console.log('error submit!!');
            return false;
          }
        });
      },
    // 建议输入框函数
     querySearch(queryString, cb) {
        var restaurants = this.restaurants;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      loadAll() {
        return [
          { 'value':`${this.getCurrentTime()}` },
          { 'value':`2008-08-08 08:08` },
          { 'value':`2001-01-01 00:00` },
        ];
      },
      handleSelect(item) {
        console.log(item);
      },

      // 获取当前时间
        getCurrentTime() {
          var yy = new Date().getFullYear();
          var mm = (new Date().getMonth()+1) <10 ? '0'+(new Date().getMonth()+1) : (new Date().getMonth()+1);
          var dd = new Date().getDate()<10 ? '0'+new Date().getDate() : new Date().getDate();
          var hh = new Date().getHours()<10 ? '0'+new Date().getHours() : new Date().getHours();
          var mf = new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes();
          var gettime = yy+'-'+mm+'-'+dd+' '+hh+':'+mf;
          return gettime 
          }
      
    }
  };
</script>

<style lang="less" scoped>
/deep/.el-dialog__header{
  text-align: left;
}
/deep/.el-form-item__label{
  text-align: left;
}
/deep/.el-dialog__body{
  text-align: left;
  padding: 30px 50px;
}
</style>